package cn.easyplatform.studio.web.views.impl;

import cn.easyplatform.lang.Strings;
import cn.easyplatform.studio.utils.StudioServiceFileUtils;
import cn.easyplatform.studio.utils.WebUtils;
import cn.easyplatform.studio.web.editors.EditorCallback;
import org.apache.commons.io.FileUtils;
import org.zkoss.image.AImage;
import org.zkoss.util.media.Media;
import org.zkoss.util.resource.Labels;
import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.Events;
import org.zkoss.zk.ui.event.UploadEvent;
import org.zkoss.zul.*;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.List;

import static cn.easyplatform.studio.utils.FileUtil.mkdirForNoExists;

public class ModuleImageView extends AbstractView<List<String>> {
    private Grid grid;

    private List<String> pathList;
    protected ModuleImageView(EditorCallback<List<String>> cb, List<String> pathList, Component component) {
        super(component, cb);
        this.pathList = pathList;
        this.pathList.add("");
    }

    @Override
    protected void createContent(Component parent) {
        grid = new Grid();
        grid.setOddRowSclass("none");
        grid.setId("themeContentView_grid_result");
        grid.setHflex("1");
        grid.setVflex("1");

        Rows rows = new Rows();
        grid.appendChild(rows);
        grid.setParent(parent);
        createRows();

        parent.getParent().getParent().addEventListener(Events.ON_CLOSE, this);
    }

    private void createRows() {
        Rows rows = grid.getRows();
        for (int i = 0; i < pathList.size(); i = i + 3) {
            Row row = new Row();
            row.setHeight("50%");
            int maxJ = i + 2 < pathList.size()? 3: pathList.size() - i;
            for (int j = 0; j < maxJ; j++) {
                String path = pathList.get(i + j);
                Vlayout vlayout = new Vlayout();
                vlayout.setWidth("250px");
                vlayout.setHeight("288px");
                vlayout.setStyle("text-align: center;border: 3px solid #F2F2F2;");
                Image themePic = new Image();
                themePic.setHflex("1");
                themePic.setHeight("250px");
                File pathFile = new File(path);
                if (pathFile.exists()) {
                    try {
                        themePic.setContent(new AImage(pathFile.getName(), new FileInputStream(path)));
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                themePic.setParent(vlayout);

                Hlayout hlayout = new Hlayout();
                hlayout.setVflex("1");
                hlayout.setId((i + j) + "");
                Button updateBtn = new Button();
                updateBtn.setLabel(Labels.getLabel("editor.file.img.btnImgUpload"));
                updateBtn.setUpload("true,maxsize=300");
                updateBtn.setIconSclass("z-icon-picture-o");
                updateBtn.setParent(hlayout);
                updateBtn.addEventListener(Events.ON_UPLOAD, this);
                if (Strings.isBlank(path) == false) {
                    Button deleteBtn = new Button();
                    deleteBtn.setLabel(Labels.getLabel("button.delete"));
                    deleteBtn.setIconSclass("z-icon-minus");
                    deleteBtn.setParent(hlayout);
                    deleteBtn.addEventListener(Events.ON_CLICK, this);
                }
                hlayout.setParent(vlayout);
                vlayout.setParent(row);
            }
            row.setParent(rows);
        }
    }

    @Override
    public void onEvent(Event event) throws Exception {
        if (event.getName().equals(Events.ON_UPLOAD)) {
            UploadEvent evt = (UploadEvent) event;
            org.zkoss.util.media.Media media = evt.getMedia();
            if (media instanceof org.zkoss.image.Image) {
                String path = copyMediaToFile(media);
                Integer index = Integer.parseInt(event.getTarget().getParent().getId());
                pathList.set(index, path);
                if (index + 1 == pathList.size())
                    pathList.add("");
                grid.getRows().getChildren().clear();
                createRows();
            } else {
                //Messagebox.show("Not an image: " + media, "Error", Messagebox.OK, Messagebox.ERROR);
                WebUtils.showError(Labels.getLabel("file.upload.error"));
            }
        } else if (event.getName().equals(Events.ON_CLICK)) {
            Integer index = Integer.parseInt(event.getTarget().getParent().getId());
            pathList.remove(index);
            if (pathList.size() == 0)
                pathList.add("");
            grid.getRows().getChildren().clear();
            createRows();
        } else if (event.getName().equals(Events.ON_CLOSE)) {
            pathList.remove(pathList.size() - 1);
            cb.setValue(pathList);
        }
    }

    private String copyMediaToFile(Media media) {
        mkdirForNoExists(new StudioServiceFileUtils().module_app);
        try {
            String mediaPath = new StudioServiceFileUtils().module_app + File.separator + media.getName();
            FileUtils.copyInputStreamToFile(media.getStreamData(), new File(mediaPath));
            return mediaPath;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
